import React, { Component } from 'react';
import './App1.scss'
import request from './utils'
import ListItem from './components/ListItem'
import ListAdd from './components/ListAdd'
class App1 extends Component {
  state = {
    todolist: [],
    num1: 0,
    num2: 0,
  }

  handleChangeChecked = (id) => {
    const { todolist } = this.state
    // 通过找到修改的数据
    const item = todolist.find(v => v.id === id)
    // 自身checked 取反
    item.isChecked = !item.isChecked

    this.setState({
      todolist,
    }, () => {
      this.computeCount()
    })

  }

  handleDeleteItem = (id) => {
    const { todolist } = this.state

    const newTodolist = todolist.filter(v => v.id !== id)

    this.setState({
      todolist: newTodolist
    }, () => {
      this.computeCount()
    })
  }
  handleAddItem = (value) => {
    const { todolist } = this.state

    todolist.push({
      title: value,
      id: new Date().getTime().toString(),
      isChecked: false
    })

    this.setState({
      todolist,
    }, () => {
      this.computeCount()
    })
  }

  computeCount() {
    let num1 = 0, num2 = 0;
    const { todolist } = this.state

    todolist.forEach(v => {
      v.isChecked ? num1++ : num2++
    })

    this.setState({
      num1,
      num2
    })
  }
  render() {
    const { todolist, num1, num2 } = this.state
    return (
      <div className="app">
        <div className="header">
          <ListAdd handleAddItem={ this.handleAddItem }></ListAdd>
        </div>

        <div className="content">
          <ListItem
            todolist={todolist}
            num={num2}
            handleChangeChecked={ this.handleChangeChecked }
            handleDeleteItem={ this.handleDeleteItem }
            flag={ false }
            title='正在进行'
          ></ListItem>

          <ListItem
            todolist={todolist}
            num={num1}
            handleChangeChecked={ this.handleChangeChecked }
            handleDeleteItem={ this.handleDeleteItem }
            flag={ true }
            title='已经完成' 
          ></ListItem>
        </div>


      
      </div>
    );
  }

  componentDidMount() {
    this.getTodolist()
  }
  // 
  // componentDidUpdate(prevProps, prevState) {
  //   console.log(prevState.todolist === this.state.todolist);
  //   if(prevState.todolist !== this.state.todolist) {
  //     this.computeCount()
  //   }
  // }
  async getTodolist() {
    // 请求数据
    const resp = await request({
      url: '/api/todolist',
      method: 'get'
    })
    // 解构数据
    const { data } = resp.data

    // 设置数据
    this.setState({
      todolist: data
    }, () => {
      this.computeCount()
    })
    
  }
}

export default App1;
